<?php
//   +----------------------------------------------------------------------
//   | Copyright (c) 2015-2025 http://www.hdphp.cn All rights reserved.
//   | Licensed ( http://www.hdphp.cn/licenses/ )
//   | Author: Jack <sophia2152@qq.com>
//   | 官方网址: http://www.hdphp.cn
//   | 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用。
//   | 任何企业和个人不允许对程序代码以任何形式任何目的再发布。
//   +----------------------------------------------------------------------
namespace app\common\services\system;

use app\common\dao\system\SystemMenusDao;
use app\common\services\BaseServices;
use hdphp\utils\Arr;

/**
 * Class：系统菜单服务
 * 创建人：Jack
 * 创建时间：2024/1/12 16:21
 * @package app\services\system
 * @mixin SystemMenusDao
 */
class SystemMenusServices extends BaseServices
{
    /**
     * @var string[]
     */
    protected $type = [
        1 => 'admin',// 平台
        2 => 'store',// 门店
        3 => 'cashier',// 收银台
        4 => 'supplier',// 供应商
    ];

    /**
     * 构造函数
     * @param SystemMenusDao $dao
     */
    public function __construct(SystemMenusDao $dao)
    {
        $this->dao = $dao;
    }

    /**
     * 注释：获取菜单没有被修改器修改的数据
     * 创建人：Jack
     * 创建时间：2024/1/12 16:28
     * @param     $menusList
     * @param int $type
     * @return array
     */
    public function getMenusData($menusList, int $type = 1)
    {
        $data = [];
        foreach ($menusList as $item) {
//            $item['expand'] = true;
            $item['selected'] = false;
            $item['title'] = $item['menu_name'];
            $item['menu_path'] = preg_replace('/^\/' . ($this->type[$type] ?? 'admin') . '/', '', $item['menu_path']);
            $data[] = $item->getData();
        }
        return $data;
    }

    /**
     * 注释：获取后台权限菜单和权限
     * 创建人：Jack
     * 创建时间：2024/1/12 16:28
     * @param     $rouleId
     * @param int $level
     * @param int $type
     * @return array
     */
    public function getMenusList($rouleId, int $level, int $type = 1)
    {
        $rulesStr = '';
        if ($level) {
            // 超级管理员查询所有菜单
            /** @var SystemRoleServices $systemRoleServices */
            $systemRoleServices = app()->make(SystemRoleServices::class);
            $rules = $systemRoleServices->getRoleArray(['status' => 1, 'id' => $rouleId], $type == 3 ? 'cashier_rules' : 'rules');
            $rulesStr = Arr::unique($rules);
        }
        $menusList = $this->dao->getMenusRoule(['type' => $type, 'route' => $level ? $rulesStr : '']);
        $unique = $this->dao->getMenusUnique(['type' => $type, 'unique' => $level ? $rulesStr : '']);
        return [Arr::getMenuIviewList($this->getMenusData($menusList, $type)), $unique];
    }


    /**
     * 注释：获取后台菜单树型结构列表
     * 创建人：Jack
     * 创建时间：2024/1/24 9:57
     * @param array $where
     * @return mixed
     */
    public function getList(array $where)
    {
        $menusList = $this->dao->getMenusList($where);
        $menusList = $this->getMenusData($menusList);
        return get_tree_children($menusList);
    }


}
